import cgi
import os

from google.appengine.ext.webapp import template
from google.appengine.api import datastore
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from django.utils import simplejson

import datamodel
import tvdb
from rpc_admin_methods import RPCAdminMethods

class Administrator(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            current_user = user.nickname()
            data = self.load_data()
            template_values = {
                'current_user': current_user,
                'logout_url': users.create_logout_url(self.request.uri),
                'users': data.get('users', []),
                'series': data.get('series', []),
                'cant': data.get('cant', 0),
                'cantSeries': data.get('cantSeries', 0),
                'without': data.get('without', []),
                'withcount': data.get('withcount', 0)
            }
            
            path = os.path.join(os.path.dirname(__file__), "templates/admin.html")
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect(users.create_login_url(self.request.uri))
            
    def load_data(self):
        data = {}
        try:
            users = tvdb.obtain_actual_users()
            data['users'] = users
            data['cant'] = len(users)
        except:
            pass
        try:
            series = tvdb.obtain_list_series()
            data['series'] = series
            data['cantSeries'] = len(series)
        except:
            pass
        try:
            without = tvdb.series_without_episodes()
            data['without'] = without
            data['withcount'] = len(without)
        except:
            pass
        return data
        
        
class RPCAdminHandler(webapp.RequestHandler):
    
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCAdminMethods()
        
    def get(self):
        func = None
        
        action = self.request.get('action')
        if action:
            if action[0] == '_':
                self.error(403) # access denied
                return
            else:
                func = getattr(self.methods, action, None)
                
        if not func:
            self.error(404) # file not found
            return
            
        args = ()
        while True:
            key = 'arg%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (simplejson.loads(val),)
            else:
                break
        result = func(*args)
        self.response.out.write(simplejson.dumps(result))
        

def main():
    application = webapp.WSGIApplication([
        ('/admin', Administrator),
        ('/adminrpc', RPCAdminHandler)
        ], debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
